package com.originskyseed.platform.cms.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.originskyseed.platform.cms.i18n.CmsResponseMsg;
import com.originskyseed.platform.cms.model.CmsMail;
import com.originskyseed.platform.cms.model.CmsMailRelFile;
import com.originskyseed.platform.cms.model.CmsMailRelReceive;
import com.originskyseed.platform.cms.service.ICmsMailRelFileService;
import com.originskyseed.platform.cms.service.ICmsMailRelReceiveService;
import com.originskyseed.platform.cms.service.ICmsMailService;
import com.originskyseed.platform.cms.vo.request.CmsMailRequestVO;
import com.originskyseed.platform.core.aspect.annotation.RequiredParams;
import com.originskyseed.platform.core.base.BaseController;
import com.originskyseed.platform.core.base.BaseLocaleResource;
import com.originskyseed.platform.core.base.BasePage;
import com.originskyseed.platform.core.base.BaseResponseBody;
import com.originskyseed.platform.core.common.code.CommonResponseCode;
import com.originskyseed.platform.core.filter.helper.SingleSignOnTokenHelper;
import com.originskyseed.platform.core.mail.api.SendMailUtil;
import com.originskyseed.platform.core.mail.bean.MailMessage;
import com.originskyseed.platform.user.model.UserInfo;

/**
 * 邮件信息表Controller类（OSI_MAIL）
 *
 * @author wlj
 */
@Controller
@RequestMapping("/cmsMail")
@BaseLocaleResource(localeFileName = "i18n_cms")
public class CmsMailController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(CmsMailController.class);

	@DubboReference
	private ICmsMailService cmsMailService;

	@DubboReference
	private ICmsMailRelFileService cmsMailRelFileService;

	@DubboReference
	private ICmsMailRelReceiveService cmsMailRelReceiveService;

	/**
	 * 分页查询
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/cmsMailList.json", method = RequestMethod.POST)
	@RequiredParams(names = { "pageNo", "pageSize" })
	public BaseResponseBody<BasePage<CmsMail>> cmsMailList(HttpServletRequest request) {
		BaseResponseBody<BasePage<CmsMail>> result = null;
		try {
			// 请求对象
			CmsMailRequestVO requestVO = this.getParameterBean(CmsMailRequestVO.class);

			// 分页查询
			BasePage<CmsMail> page = new BasePage<CmsMail>(requestVO.getPageNo(), requestVO.getPageSize());
			page = this.cmsMailService.selectListByPage(requestVO.toMap(), page);
			result = new BaseResponseBody<BasePage<CmsMail>>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.DATA_LIST_SUCCESS.getMsg()), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<BasePage<CmsMail>>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 保存信息
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/cmsMailSave.json", method = RequestMethod.POST)
	@RequiredParams(names = {})
	public BaseResponseBody<CmsMail> cmsMailSave(HttpServletRequest request) {
		BaseResponseBody<CmsMail> result = null;
		try {
			// 请求对象
			CmsMail cmsMail = this.getParameterBean(CmsMail.class);
			List<CmsMailRelFile> cmsMailRelFileList = this.getParameterList("cmsMailRelFileList",CmsMailRelFile.class);//附件
			List<CmsMailRelReceive> cmsMailRelReceiveList = this.getParameterList("cmsMailRelReceiveList",CmsMailRelReceive.class);//接收对象
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			if (StringUtils.isNotBlank(cmsMail.getId())) {
				this.cmsMailService.updateEmail(cmsMail,userInfo,cmsMailRelFileList,cmsMailRelReceiveList);
			} else {
				//接收人
				List<String> objEmail = new ArrayList<>();
				//附件
				List<String> fileList = new ArrayList<>();
				if(cmsMail.getFromObjMail() != null && StringUtils.isNotBlank(cmsMail.getFromObjMail())){
					if(cmsMail.getFromObjMail().matches("^[a-z0-9A-Z]+[- | a-z0-9A-Z . _]+@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-z]{2,}$") == false){
						return new BaseResponseBody<CmsMail>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.SENDER_EMAIL_ERROR.getMsg()), null);
					}
				}else {
					cmsMail.setFromObjId(userInfo.getId());
					cmsMail.setFromObjName(userInfo.getName());
					if (userInfo.getEmail().matches("^[a-z0-9A-Z]+[- | a-z0-9A-Z . _]+@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-z]{2,}$")) {
						cmsMail.setFromObjMail(userInfo.getEmail());
					} else {
						return new BaseResponseBody<CmsMail>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.SENDER_EMAIL_ERROR.getMsg()), null);
					}
				}
				if (cmsMail.getStatus() != null && cmsMail.getStatus() == 1) { //新增即发布
					if(cmsMailRelReceiveList != null && cmsMailRelReceiveList.size() > 0){
						for (CmsMailRelReceive cmsMailRelReceive : cmsMailRelReceiveList) {
							if(cmsMailRelReceive.getObjMail() != null && StringUtils.isNotBlank(cmsMailRelReceive.getObjMail())){
								if(cmsMailRelReceive.getObjMail().matches("^[a-z0-9A-Z]+[- | a-z0-9A-Z . _]+@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-z]{2,}$")) {
									objEmail.add(cmsMailRelReceive.getObjMail());
								}
							}
						}
						if(cmsMailRelFileList != null && cmsMailRelFileList.size() >0){
							for (CmsMailRelFile cmsMailRelFile : cmsMailRelFileList) {
								if(cmsMailRelFile.getFilePath() != null && StringUtils.isNotBlank(cmsMailRelFile.getFilePath())){
									fileList.add(cmsMailRelFile.getFilePath());
								}
							}
						}
						if(objEmail != null && objEmail.size() >0){
							MailMessage mailMessage = new MailMessage();
							mailMessage.setSubject(cmsMail.getTitle()==null?"":cmsMail.getTitle());
							mailMessage.setRecipients(objEmail);
							String content =  SendMailUtil.readHtmlContent(request.getServletContext().getRealPath("/email_template/SendStock.html"));
							content = content.replaceAll("\\{\\{title\\}\\}",cmsMail.getContent()==null?"":cmsMail.getContent());
							mailMessage.setContent(content);
							if(fileList != null && fileList.size() >0){
								mailMessage.setAttachments(Arrays.asList(fileList.toArray()));
							}
							cmsMail.setStatus(1);
							SendMailUtil.sendMail(mailMessage);//发送邮件
						}else {
							return new BaseResponseBody<CmsMail>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.MAIL_ISNULL_ERROR.getMsg()), null);
						}
					}else {
						return new BaseResponseBody<CmsMail>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.MAIL_ISNULL_ERROR.getMsg()), null);
					}
				}else {
					cmsMail.setStatus(0);
				}
				this.cmsMailService.insertEmail(cmsMail,userInfo,cmsMailRelFileList,cmsMailRelReceiveList);
			}
			result = new BaseResponseBody<CmsMail>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.MAIL_SAVE_SUCCESS.getMsg()), cmsMail);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<CmsMail>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.MAIL_SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 详情
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/detailsByMailId.json", method = RequestMethod.POST)
	@RequiredParams(names = {"id"})
	public BaseResponseBody<CmsMail> detailsByMailId(HttpServletRequest request) {
		BaseResponseBody<CmsMail> result = null;
		try {
			// 请求对象
			String id = this.getParameterString("id",null);
			CmsMail cmsMail = this.cmsMailService.selectByPrimaryKey(id);
			if(cmsMail != null){
				CmsMailRelReceive cmsMailRelReceive = new CmsMailRelReceive();
				CmsMailRelFile cmsMailRelFile = new CmsMailRelFile();
				cmsMailRelReceive.setMailId(id);
				cmsMailRelFile.setMailId(id);
				List<CmsMailRelReceive> cmsMailRelReceiveList = this.cmsMailRelReceiveService.selectList(cmsMailRelReceive);
				cmsMail.setCmsMailRelReceiveList(cmsMailRelReceiveList);
				List<CmsMailRelFile> cmsMailRelFileList = this.cmsMailRelFileService.selectList(cmsMailRelFile);
				cmsMail.setCmsMailRelFileList(cmsMailRelFileList);
			}else {
				cmsMail = new CmsMail();
			}
			result = new BaseResponseBody<CmsMail>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.DATA_SUCCESS.getMsg()), cmsMail);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<CmsMail>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.DATA_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 发布
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/sendEmail.json", method = RequestMethod.POST)
	@RequiredParams(names = {"id"})
	public BaseResponseBody<Boolean> sendEmail(HttpServletRequest request) {
		BaseResponseBody<Boolean> result = null;
		try {
			// 请求对象
			String id = this.getParameterString("id",null);
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			CmsMail cmsMail = this.cmsMailService.selectByPrimaryKey(id);
			//接收人
			CmsMailRelReceive cmsMailRelReceive = new CmsMailRelReceive();
			CmsMailRelFile cmsMailRelFile = new CmsMailRelFile();
			cmsMailRelReceive.setMailId(id);
			cmsMailRelFile.setMailId(id);
			List<CmsMailRelReceive> cmsMailRelReceiveList = this.cmsMailRelReceiveService.selectList(cmsMailRelReceive);
			List<CmsMailRelFile> cmsMailRelFileList = this.cmsMailRelFileService.selectList(cmsMailRelFile);
			if(cmsMail != null && cmsMailRelReceiveList != null && cmsMailRelReceiveList.size() > 0){
				MailMessage mailMessage = new MailMessage();
				//mailMessage.setSender(userInfo.getEmail());
				mailMessage.setSubject(cmsMail.getTitle()==null?"":cmsMail.getTitle());
				List<String> email = new ArrayList<>();
				for (CmsMailRelReceive mailRelReceive : cmsMailRelReceiveList) {
					if(mailRelReceive.getObjMail() != null && StringUtils.isNotBlank(mailRelReceive.getObjMail())){
						if(mailRelReceive.getObjMail().matches("^[a-z0-9A-Z]+[- | a-z0-9A-Z . _]+@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-z]{2,}$")) {
							email.add(mailRelReceive.getObjMail());
						}
					}
				}
				if(email == null || email.size() == 0){
					return new BaseResponseBody<Boolean>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.MAIL_ISNULL_ERROR.getMsg()), null);
				}
				mailMessage.setRecipients(email);
				String content =  SendMailUtil.readHtmlContent(request.getServletContext().getRealPath("/email_template/SendStock.html"));
				content = content.replaceAll("\\{\\{title\\}\\}",cmsMail.getContent()==null?"":cmsMail.getContent());
				mailMessage.setContent(content);
				//附件
				List<String> fileList= new ArrayList<>();
				if(cmsMailRelFileList != null && cmsMailRelFileList.size() > 0){
					for (CmsMailRelFile mailRelFile : cmsMailRelFileList) {
						if(mailRelFile.getFilePath() != null && StringUtils.isNotBlank(mailRelFile.getFilePath())){
							fileList.add(mailRelFile.getFilePath());
						}
					}
				}
				if(fileList != null && fileList.size() >0){
					mailMessage.setAttachments(Arrays.asList(fileList.toArray()));
				}
				SendMailUtil.sendMail(mailMessage);//发送邮件
				//更新状态
				cmsMail.setStatus(1);
				this.cmsMailService.updateByPrimaryKeySelective(cmsMail);
			}else {
				return new BaseResponseBody<Boolean>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.MAIL_ISNULL_ERROR.getMsg()), null);
			}
			result = new BaseResponseBody<Boolean>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.MAIL_SEND_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<Boolean>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.MAIL_SEND_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 删除信息
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/cmsMailDelete.json", method = RequestMethod.POST)
	@RequiredParams(names = { "ids" })
	public BaseResponseBody<Boolean> cmsMailDelete(HttpServletRequest request) {
		BaseResponseBody<Boolean> result = null;
		try {
			// 请求参数
			String[] ids = this.getParameterArray("ids", new String[] {});

			this.cmsMailService.deleteByIds(Arrays.asList(ids));
			result = new BaseResponseBody<Boolean>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.MAIL_DELETE_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<Boolean>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.MAIL_DELETE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	//测试邮件
	public static void main(String[] args) throws Exception {
		Properties props = config();
		// 构建授权信息，用于进行SMTP进行身份验证
		Authenticator authenticator = new Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				// 用户名、密码
				String userName = props.getProperty("mail.user");
				String password = props.getProperty("mail.password");
				return new PasswordAuthentication(userName, password);
			}
		};
		// 使用环境属性和授权信息，创建邮件会话
		Session mailSession = Session.getInstance(props, authenticator);
        // 创建邮件消息
		MimeMessage message = new MimeMessage(mailSession);
		// 设置发件人
		InternetAddress form = new InternetAddress(props.getProperty("mail.user"));
		message.setFrom(form);
		// 设置收件人的邮箱
		List<String> email = new ArrayList<>();
		email.add("***@163.com");
		email.add("*****@qq.com");
		InternetAddress[] to_email = new InternetAddress[email.size()];
		for (int i = 0; i < email.size(); i++) {
			to_email[i] = new InternetAddress(String.valueOf(email.get(i)));
		}
		//InternetAddress to = new InternetAddress(email.size());
		//message.setRecipient(Message.RecipientType.TO, to);
		message.setRecipients(Message.RecipientType.TO,to_email);

		// 设置邮件标题
		message.setSubject("====test====");

		//收件人
		//List<String> email = new ArrayList<>();
		//email.add("***@163.com");
		//message.setRecipients(Message.RecipientType.TO, String.valueOf(email));

		// 设置邮件的内容体
		//message.setContent("新闻联播", "text/html;charset=UTF-8");

		/*MimeBodyPart messageBodyPart =new MimeBodyPart();
		Multipart multipart = new MimeMultipart();
		multipart.addBodyPart(messageBodyPart);
		File attachment;
		attachment= new File("E:/video/青玉案-元夕.txt");
		DataSource fileDataSource=new FileDataSource(attachment);
		messageBodyPart.setDataHandler(new DataHandler(fileDataSource));
		messageBodyPart.setFileName(attachment.getName());
		multipart.addBodyPart(messageBodyPart);
		message.setContent(multipart);*/

		//文本
		//String content = SendMailUtil.readHtmlContent("E:/video/青玉案-元夕.txt");
		//String content = SendMailUtil.readHtmlContent("E:/video/video02.mp4");
		String content = SendMailUtil.readHtmlContent("E:/video/video02.mp4");
		content = content.replaceAll("\\{\\{title\\}\\}","==============ceshi=================");
		message.setContent(content.toString(),"text/html;charset=UTF-8");
		//message.setText("明月别枝惊鹊，清风半夜鸣蝉。稻花香里说丰年，听取蛙声一片。","text/html;charset=UTF-8");
		Transport.send(message);
	}

	/**
	 * 自定义配置
	 */
	private static Properties config(){
		Properties props = new Properties();
		// 表示SMTP发送邮件，必须进行身份验证
		props.put("mail.smtp.auth", "true");
		//此处填写SMTP服务器
		props.put("mail.smtp.host", "smtp.qq.com");
		//端口号，QQ邮箱端口587
		props.put("mail.smtp.port", "587");
		// 此处填写，写信人的账号
		props.put("mail.user", "*****@qq.com");
		// 此处填写16位STMP口令
		props.put("mail.password", "******");
		return props;
	}
}
